package com.yt.order.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.yt.common.enums.CodeEnum;
import com.yt.common.exception.BusinessException;
import com.yt.order.common.config.YmlConfig;
import com.yt.order.models.bo.WorkOrderEvaluationSaveBO;
import com.yt.order.models.bo.WorkOrderEvaluationQueryBO;
import com.yt.order.models.dto.WorkOrderEvaluationDTO;
import com.yt.order.models.service.IWorkOrderEvaluationService;
import com.yt.order.mapper.WorkOrderEvaluationMapper;
import com.yt.order.models.vo.WorkOrderEvaluationVO;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@DubboService
@Service
public class WorkOrderEvaluationServiceImpl extends ServiceImpl<WorkOrderEvaluationMapper, WorkOrderEvaluationDTO>
        implements IWorkOrderEvaluationService {

    @Resource
    private YmlConfig ymlConfig;

    @Resource
    private WorkOrderEvaluationMapper evaluationMapper;

    @Override
    public boolean add(WorkOrderEvaluationSaveBO saveBO) {
        // 参数校验
        validateSaveBO(saveBO, true);

        WorkOrderEvaluationDTO dto = new WorkOrderEvaluationDTO();
        BeanUtils.copyProperties(saveBO, dto);

        // 自动生成ID
        dto.setId(ymlConfig.getPkId());
        // 默认值设置
        dto.setStatus(1); // 有效状态
        dto.setRevision(0); // 初始版本号
        Date now = new Date();
        dto.setCreateTime(now);
        dto.setUpdateTime(now);

        return this.insert(dto);
    }

    @Override
    public boolean updateEvaluation(WorkOrderEvaluationSaveBO saveBO) {
        // 参数校验
        validateSaveBO(saveBO, false);

        // 检查评价是否存在
        WorkOrderEvaluationDTO existing = this.selectById(saveBO.getId());
        if (existing == null) {
            throw new BusinessException(CodeEnum.FAIL_100010.getCode(), "评价记录不存在");
        }

        WorkOrderEvaluationDTO dto = new WorkOrderEvaluationDTO();
        BeanUtils.copyProperties(saveBO, dto);
        dto.setUpdateTime(new Date()); // 更新时间

        // 乐观锁控制（依赖MyBatis-Plus乐观锁插件）
        return this.updateById(dto);
    }

    @Override
    public boolean logicDelete(Long id) {
        if (id == null) {
            throw new BusinessException(CodeEnum.FAIL_100002.getCode(), "评价ID不能为空");
        }

        WorkOrderEvaluationDTO dto = new WorkOrderEvaluationDTO();
        dto.setId(id);
        dto.setStatus(0); // 无效状态
        dto.setUpdateTime(new Date());
        return this.updateById(dto);
    }

    @Override
    public WorkOrderEvaluationDTO getByOrderId(Long orderId) {
        if (orderId == null) {
            throw new BusinessException(CodeEnum.FAIL_100002.getCode(), "工单ID不能为空");
        }
        return evaluationMapper.selectByOrderId(orderId);
    }

    @Override
    public Page<WorkOrderEvaluationVO> queryEmpEvaluations(WorkOrderEvaluationQueryBO bo) {
        if (bo.getEmpId() == null) {
            throw new BusinessException(CodeEnum.FAIL_100002.getCode(), "员工ID不能为空");
        }
        // 校验分页参数
        int pageNo = bo.getPageNo() == null ? 1 : bo.getPageNo();
        int pageSize = bo.getPageSize() == null ? 10 : bo.getPageSize();
        if (pageNo < 1) pageNo = 1;
        if (pageSize < 1 || pageSize > 100) pageSize = 10;
        bo.setPageNo(pageNo);
        bo.setPageSize(pageSize);

        // 手动查询总条数和当前页数据
        int total = baseMapper.countEmpEvaluations(bo);
        List<WorkOrderEvaluationVO> records = baseMapper.selectEmpEvaluations(bo);

        // 构建分页结果
        Page<WorkOrderEvaluationVO> page = new Page<>(pageNo, pageSize);
        page.setTotal(total);
        page.setRecords(records);
        return page;
    }

    @Override
    public Page<WorkOrderEvaluationVO> queryEvaluatorEvaluations(WorkOrderEvaluationQueryBO bo) {
        if (bo.getEvaluatorId() == null) {
            throw new BusinessException(CodeEnum.FAIL_100002.getCode(), "评价人ID不能为空");
        }
        // 校验分页参数
        int pageNo = bo.getPageNo() == null ? 1 : bo.getPageNo();
        int pageSize = bo.getPageSize() == null ? 10 : bo.getPageSize();
        if (pageNo < 1) pageNo = 1;
        if (pageSize < 1 || pageSize > 100) pageSize = 10;
        bo.setPageNo(pageNo);
        bo.setPageSize(pageSize);

        // 手动查询总条数和当前页数据
        int total = baseMapper.countEvaluatorEvaluations(bo);
        List<WorkOrderEvaluationVO> records = baseMapper.selectEvaluatorEvaluations(bo);

        // 构建分页结果
        Page<WorkOrderEvaluationVO> page = new Page<>(pageNo, pageSize);
        page.setTotal(total);
        page.setRecords(records);
        return page;
    }

    /**
     * 参数校验
     * @param saveBO 保存参数
     * @param isAdd 是否为新增操作
     */
    private void validateSaveBO(WorkOrderEvaluationSaveBO saveBO, boolean isAdd) {
        if (saveBO == null) {
            throw new BusinessException(CodeEnum.FAIL_100001.getCode(), "评价参数不能为空");
        }

        if (isAdd) {
            // 新增时必传参数校验
            if (saveBO.getOrderId() == null) {
                throw new BusinessException(CodeEnum.FAIL_100002.getCode(), "工单ID不能为空");
            }
            if (saveBO.getEmpId() == null) {
                throw new BusinessException(CodeEnum.FAIL_100002.getCode(), "被评价员工ID不能为空");
            }
        } else {
            // 更新时必传参数校验
            if (saveBO.getId() == null) {
                throw new BusinessException(CodeEnum.FAIL_100002.getCode(), "评价ID不能为空");
            }
            if (saveBO.getRevision() == null) {
                throw new BusinessException(CodeEnum.FAIL_100002.getCode(), "版本号不能为空");
            }
        }

        // 星级校验（1-5星）
        if (saveBO.getRating() != null && (saveBO.getRating() < 1 || saveBO.getRating() > 5)) {
            throw new BusinessException(CodeEnum.FAIL_100003.getCode(), "评价星级必须为1-5星");
        }
    }
}